package com.example.code.effective.article47;

import java.util.*;

public class PowerSet {
    // Returns the power set of an input set as custom collection (Page 218)
    public static final <E> Collection<Set<E>> of(Set<E> s) {
        List<E> src = new ArrayList<>(s);
        if (src.size() > 30) {
            throw new IllegalArgumentException("Set too big " + s);
        }
        return new AbstractList<Set<E>>() {
            @Override
            public int size() {
                return 1 << src.size(); // 2 to the power srcSize
            }

            @Override
            public boolean contains(Object o) {
                return o instanceof Set && src.containsAll((Set) o);
            }

            @Override
            public Set<E> get(int index) {
                Set<E> result = new HashSet<>();
                for (int i = 0; index != 0; i++, index >>= 1) {
                    System.out.println(index);
                    if ((index & 1) == 1) {
                        result.add(src.get(i));
                    }
                }
                System.out.println("调用get：" + result.toString());
                return result;
            }
        };
    }

    public static void main(String[] args) {
        Set<Integer> s = new HashSet(Arrays.asList(1, 2, 3, 4));
        Collection<Set<Integer>> of = PowerSet.of(s);
        System.out.println(of);

        List<Integer> integers = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
        for (Integer integer : integers) {
            // System.out.print("integer :" + integer);
            System.out.print(integer + " & 1 : " + (integer & 1));
            //System.out.print("; " + integer + " >>= 1 : " + (integer >>= 1));
            System.out.println("; " + integer + " >> 1 : " + (integer >> 1));
        }

    }

    /**
     * {} index = 0
     * {1}
     *
     */
}